'use strict';
const db = uniCloud.database()
const {
  Base64
} = require("base64")
exports.main = async (event, context) => {
  //event为客户端上传的参数
  console.log('event : ', event)
  let base = new Base64()
  const res = await db.collection('article').get()
  let newArr = []
  let newCollection = []
  // 循环查找每个收藏id对应的数据
  for (let i = 0; i < event.collection.length; i++) {
    let id = event.collection[i]
    let obj = res.data.filter(item => item._id == id)
    if (obj) {
      newArr.push(...obj)
    }
  }
  // 更新用户收藏列表信息，确保当前收藏内容是存在于数据库的
  for (let i = 0; i < newArr.length; i++) {
    delete newArr[i].openid
    newCollection.push(newArr[i]._id)
  }
  const a = await db.collection("users").where({
    openid: JSON.parse(base.decode(event.openid))
  }).update({
    collection: newCollection
  })
  //返回数据给客户端
  return newArr
};
